package cn.gov.msa.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

import cn.gov.msa.dao.ReserveMapper;
import cn.gov.msa.dao.RuleMapper;
import cn.gov.msa.dao.RuleTimeMapper;
import cn.gov.msa.model.DeclareItem;
import cn.gov.msa.model.Reserve;
import cn.gov.msa.model.Rule;
import cn.gov.msa.model.RuleTime;
import cn.gov.msa.pagehelper.CustomPageHelper;
import cn.gov.msa.service.ReserveService;

public class ReserveServiceImpl implements ReserveService {

	@Autowired
	private ReserveMapper reserveMapper;
	@Autowired
	private RuleMapper ruleMapper;
	@Autowired
	private RuleTimeMapper ruleTimeMapper;

	@Transactional
	@Override
	public List<Reserve> selectData(int pageNum, int pageSize, Reserve reserve) {
		CustomPageHelper.startPage(pageNum, pageSize); // 核心分页代码
		List<Reserve> list = reserveMapper.selectData(reserve);
		return list;
	}

	@Transactional
	@Override
	public List<Reserve> selectData(Reserve reserve) {
		List<Reserve> list = reserveMapper.selectData(reserve);
		return list;
	}

	@Transactional
	@Override
	public List<DeclareItem> selectItem(String declareItem) {
		return reserveMapper.selectItem(declareItem);
	}

	@Transactional
	@Override
	public int updateState(Reserve reserve) {
		// TODO Auto-generated method stub
		return reserveMapper.updateState(reserve);
	}

	@Transactional
	@Override
	public int deleteData(Reserve reserve) {
		// TODO Auto-generated method stub
		return reserveMapper.deleteData(reserve);
	}

	@Transactional
	@Override
	public int insertData(Reserve reserve) {
		// TODO Auto-generated method stub
		return reserveMapper.insertData(reserve);
	}

	@Transactional
	@Override
	public String check(Reserve reserve) {
		// TODO Auto-generated method stub
		return reserveMapper.check(reserve);
	}

	@Override
	public String getNum(Reserve reserve, String[] times) {
		// TODO Auto-generated method stub
		Rule rule = new Rule();
		rule.setItemid(reserve.getITEMID());
		rule.setOrgcode(reserve.getORGCODE());
		List<Rule> ruleList = this.ruleMapper.selectData(rule);// 获取规则
		int maxNum = 0, nowNum = 0;
		for (int i = 0; i < times.length; i++) {
			if(ruleList.size() == 0){
				break;
			}
			reserve.setRECORDPERIOD(times[i]);
			List<RuleTime> ruleTimeList = this.ruleTimeMapper.getMaxNum(ruleList.get(0).getRuleid(),
					reserve.getRECORDPERIOD());
			if (ruleTimeList.size() == 0) {
				times[i] = "-1"; // 无预约记录
			} else {
				maxNum = ruleTimeList.get(0).getReservenum(); // 最大人数
				if (maxNum != 0) {
					nowNum = this.reserveMapper.getNum(reserve); // 当前人数
					times[i] = String.valueOf((maxNum - nowNum));
				}
			}
		}
		return StringUtils.join(times, ",");
	}

}
